package xyz.longicorn.driver.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.longicorn.driver.config.BizException;
import xyz.longicorn.driver.dao.FileInfoMapper;
import xyz.longicorn.driver.dao.FolderInfoMapper;
import xyz.longicorn.driver.dto.FastUploadFile;
import xyz.longicorn.driver.pojo.FileInfo;
import xyz.longicorn.driver.pojo.FolderInfo;

import javax.annotation.Resource;
import java.util.List;

@Service
public class FileService extends ServiceImpl<FileInfoMapper, FileInfo> {
    @Resource
    private FolderInfoMapper folderInfoMapper;

    /**
     * 查询了目录下的文件列表集合
     *
     * @param uid
     * @param folderId
     * @return
     */
    public List<FileInfo> listByFolderId(int uid, long folderId) {
        QueryWrapper q = new QueryWrapper();
        q.eq("uid", uid);
        q.eq("folder_id", folderId);
        q.eq("status", 1); // TODO 枚举
        return this.list(q);
    }

    public FileInfo getByMd5(String md5) {
        QueryWrapper q = new QueryWrapper();
        q.eq("hash", md5);//根据MD5查询是否已经存在改文件
        q.last("limit 1");
        return this.getOne(q);
    }

    public FileInfo fastUpload(int uid, FastUploadFile file) {
        long folderId = 0;
        if (!"/".equals(file.getFolder())) { // 不是根目录
            final FolderInfo folder = folderInfoMapper.getByPath(uid, file.getFolder());
            if (null == folder) throw BizException.create("保存目录不存在");
            folderId = folder.getId(); // 设置上传目录编号
        }

        FileInfo info = this.getByMd5(file.getHash());//查询是否存在要上传的文件
        if (info == null) return null; // 没有存在 只能走普通上传
        //
        FileInfo newFile = new FileInfo(); // 要保存的数据
        newFile.setPath(info.getPath());
        newFile.setHash(info.getHash());
        newFile.setType(file.getType());
        newFile.setFolderId(folderId);
        newFile.setUid(uid);
        newFile.setName(file.getName());
        newFile.setSize(info.getSize());
        return this.save(newFile) ? newFile : null;
    }
}
